﻿ 
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SHKF.B2C.MeiTuanShanGou.BLL;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.BLL.LM;
using SHKF.B2C.BLL.Order;
using SHKF.B2C.MeiTuanShanGou.Model.Dto;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.Order;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.OrderDetail;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.Token;
using SHKF.B2C.MeiTuanShanGou.Model.Entity.Order;
using SHKF.B2C.MeiTuanShanGou.Model.Push.Order; 
using SHKF.B2C.MeiTuanShanGou.Model.Push.Order.PoiReceiveDetailYuan;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Entity.LM;
using SkyApm.Tracing; 
using System;
using System.Collections.Generic;　
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using SHKF.B2C.BaseHosted;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.OrderIdByDaySeq;

namespace SHKF.B2C.MeiTuanShanGou.Service.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class OrderController : Base2Controller
    {
        private readonly ShopMapBLL shopMapBll;
        private readonly OrderBLL orderBLL;
        private readonly MtsgOrderBLL mtsgOrderBLL;
        private readonly MedicineBLL medicineBLL;
        private readonly RetrunOrderBLL retrunOrderBLL;

        public OrderController(
            ShopMapBLL shopMapBll,
            OrderBLL orderBLL,
            MtsgOrderBLL mtsgOrderBLL,
            MedicineBLL medicineBLL,
            IServiceProvider serviceProvider,
            ILogger<OrderController> logger) : base(serviceProvider, logger)
        {
            this.shopMapBll = shopMapBll;
            this.orderBLL = orderBLL;
            this.mtsgOrderBLL = mtsgOrderBLL;
            this.medicineBLL = medicineBLL;

            this.retrunOrderBLL = (RetrunOrderBLL)serviceProvider.GetService(typeof(RetrunOrderBLL));
        }

        [HttpGet("test")]
        public BaseDataDto Test()
        {
            return new BaseDataDto();
        }

        #region CallBack

        [HttpPost("CallBack")]
        public BaseDataDto CallBack([FromForm] OrderPush order)
        {
            try
            {
                if (order != null && order.app_poi_code > 0)
                {
                    if (order.app_poi_code > 0 && (order.status == 4 || order.status == 8))
                    {
                        string json = JsonConvert.SerializeObject(order);

                        base.AddLog("Order-CallBack->json:" + json);
                        base.WriteInformation("CallBack", "jsonData:" + json);

                        decimal poiReceive = 0;

                        //返回账目
                        List<SHKF.B2C.Model.Entity.Order.OrderAccountEntity> accounts = CreateOrderAccount(order, out poiReceive);


                        //定单
                        OrderContentEntity orderEntity = MtsgCreateOrder(order);
                        orderEntity.poiReceive = poiReceive;

                        //明细
                        List<OrderDetailEntity> list = MtsgCreateOrderDetail(order.detail, orderEntity.order_id, orderEntity.app_poi_code);

                        this.mtsgOrderBLL.SaveAll(orderEntity, list, accounts);

                        //B2C的数据
                        SHKF.B2C.Model.Entity.Order.OrderContentEntity orderEntity2 = CreateOrder(order);
                        orderEntity2.poiReceive = poiReceive;

                        //明细
                        List<SHKF.B2C.Model.Entity.Order.OrderDetailEntity> list2 = CreateOrderDetail(order.detail, orderEntity.order_id, orderEntity.app_poi_code);
                        this.orderBLL.SaveAll(orderEntity2, list2, accounts);
                    }

                }
            }
            catch (Exception ex)
            {
                this.segContext.Context.Span.ErrorOccurred(ex, null);
                base.WriteException("CallBack", ex);
            }

            BaseDataDto dto = new BaseDataDto();
            dto.data = "ok";
            return dto;
        }
         
        private SHKF.B2C.Model.Entity.Order.OrderContentEntity CreateOrder(OrderPush order)
        {
            SHKF.B2C.Model.Entity.Order.OrderContentEntity orderEntity = new SHKF.B2C.Model.Entity.Order.OrderContentEntity();

            int shopSN = 0;
            ShopMapEntity shopMap = this.shopMapBll.GetShop(order.app_poi_code, PlatformEnum.Mtsg);
            if (shopMap != null)
            {
                shopSN = shopMap.ShopSN;
            }
            orderEntity.ShopSN = shopSN;
            orderEntity.app_poi_code = order.app_poi_code;
            orderEntity.ID = order.order_id.ToString();
            orderEntity.status = order.status;
            orderEntity.order_id = order.order_id;
            orderEntity.wm_order_id_view = order.wm_order_id_view;
            orderEntity.wm_poi_name = HttpUtility.UrlDecode(order.wm_poi_name);
            orderEntity.wm_poi_address = HttpUtility.UrlDecode(order.wm_poi_address);
            orderEntity.wm_poi_phone = order.wm_poi_phone;
            orderEntity.recipient_address = HttpUtility.UrlDecode(order.recipient_address);
            orderEntity.recipient_phone = order.recipient_phone;
            orderEntity.recipient_name = HttpUtility.UrlDecode(order.recipient_name);
            orderEntity.total = order.total;
            orderEntity.total_fee = order.original_price;
            orderEntity.caution = HttpUtility.UrlDecode(order.caution);
            orderEntity.shipper_phone = order.shipper_phone;
            orderEntity.shipper_phone = order.shipper_phone;
            orderEntity.has_invoiced = order.has_invoiced;
            orderEntity.invoice_title = order.invoice_title;
            orderEntity.Platform = PlatformEnum.Mtsg;
            orderEntity.ctime = DateTimeUtil.TimeStampToDateTime(order.ctime);
            orderEntity.utime = DateTimeUtil.TimeStampToDateTime(order.utime);

            if (order.delivery_time == 0)
            {
                orderEntity.delivery_time = new DateTime(1900, 1, 1);
            }
            else
            {
                orderEntity.delivery_time = DateTimeUtil.TimeStampToDateTime(order.delivery_time);
            }

            orderEntity.day_seq = order.day_seq;

            orderEntity.total_weight = order.total_weight;
            return orderEntity;
        }
         
        private OrderContentEntity MtsgCreateOrder(OrderPush order)
        {
            OrderContentEntity orderEntity = new OrderContentEntity();
            orderEntity.app_poi_code = order.app_poi_code;
            orderEntity.ID = order.order_id.ToString();
            orderEntity.status = order.status;
            orderEntity.order_id = order.order_id;
            orderEntity.wm_order_id_view = order.wm_order_id_view;
            orderEntity.wm_poi_name = HttpUtility.UrlDecode(order.wm_poi_name);
            orderEntity.wm_poi_address = HttpUtility.UrlDecode(order.wm_poi_address);
            orderEntity.wm_poi_phone = order.wm_poi_phone;
            orderEntity.recipient_address = HttpUtility.UrlDecode(order.recipient_address);
            orderEntity.recipient_phone = order.recipient_phone;
            orderEntity.recipient_name = HttpUtility.UrlDecode(order.recipient_name);
            orderEntity.shipping_fee = order.shipping_fee;
            orderEntity.total = order.total;
            orderEntity.original_price = order.original_price;
            orderEntity.caution = HttpUtility.UrlDecode(order.caution);
            orderEntity.shipper_phone = order.shipper_phone;
            orderEntity.shipper_phone = order.shipper_phone;
            orderEntity.has_invoiced = order.has_invoiced;
            orderEntity.invoice_title = order.invoice_title;
            orderEntity.Platform = PlatformEnum.Mtsg;
            orderEntity.ctime = DateTimeUtil.TimeStampToDateTime(order.ctime);
            orderEntity.utime = DateTimeUtil.TimeStampToDateTime(order.utime);
            orderEntity.package_bag_money_yuan = order.package_bag_money_yuan;

            //string strExtras = HttpUtility.UrlDecode(order.extras);
            //[{"mt_charge":0.0,"poi_charge":4.0,"reduce_fee":4.0,"remark":"减配送费5.0元","type":25}]
            //List<extras> obj = JsonConvert.DeserializeObject<List<extras>>(strExtras); 

            if (order.delivery_time == 0)
            {
                orderEntity.delivery_time = new DateTime(1900, 1, 1);
            }
            else
            {
                orderEntity.delivery_time = DateTimeUtil.TimeStampToDateTime(order.delivery_time);
            }

            orderEntity.day_seq = order.day_seq;

            orderEntity.total_weight = order.total_weight;
            return orderEntity;
        }

        private List<OrderDetailEntity> MtsgCreateOrderDetail(string detail, long order_id, long app_poi_code)
        {
            string json = HttpUtility.UrlDecode(detail);
            List<OrderDetailPush> list2 = JsonConvert.DeserializeObject<List<OrderDetailPush>>(json);

            List<OrderDetailEntity> list = new List<OrderDetailEntity>();
            foreach (OrderDetailPush orderDetailPush in list2)
            {
                OrderDetailEntity orderDetailEntity = new OrderDetailEntity();

                orderDetailEntity.FKSN = order_id;
                orderDetailEntity.actual_price = orderDetailPush.actual_price;
                orderDetailEntity.original_price = orderDetailPush.actual_price;
                orderDetailEntity.app_medicine_code = orderDetailPush.app_medicine_code;
                orderDetailEntity.product_name = orderDetailPush.food_name;
                orderDetailEntity.upc = orderDetailPush.upc;
                orderDetailEntity.qty = orderDetailPush.quantity;
                orderDetailEntity.price = orderDetailPush.price;
                orderDetailEntity.box_num = orderDetailPush.box_num;
                orderDetailEntity.box_price = orderDetailPush.box_price;
                orderDetailEntity.unit = orderDetailPush.unit;
                orderDetailEntity.food_discount = orderDetailPush.food_discount;
                orderDetailEntity.weight = orderDetailPush.weight;
                orderDetailEntity.weight_unit = orderDetailPush.weight_unit;
                orderDetailEntity.item_id = orderDetailPush.item_id;
                orderDetailEntity.ProductSN = this.medicineBLL.GetProductSN(orderDetailPush.upc, app_poi_code);
                this.logger.LogInformation($"ProductSN :{orderDetailEntity.ProductSN} app_medicine_code:{orderDetailPush.app_medicine_code}  app_poi_code:{app_poi_code}");

                list.Add(orderDetailEntity);
            }
            return list;
        }
         
        private List<SHKF.B2C.Model.Entity.Order.OrderAccountEntity> CreateOrderAccount(OrderPush order, out decimal poiReceive)
        {
            poiReceive = 0;

            List<SHKF.B2C.Model.Entity.Order.OrderAccountEntity> list = new List<B2C.Model.Entity.Order.OrderAccountEntity>();

            //打包袋金额，单位是元
            B2C.Model.Entity.Order.OrderAccountEntity order2 = CreateAccount("打包袋金额", "package_bag_money_yuan", order.package_bag_money_yuan);
            list.Add(order2);

            string strpoi_receive_detail_yuan = HttpUtility.UrlDecode(order.poi_receive_detail_yuan);
            poi_receive_detail_yuan objpoi_receive_detail_yuan = JsonConvert.DeserializeObject<poi_receive_detail_yuan>(strpoi_receive_detail_yuan);
            if (objpoi_receive_detail_yuan != null)
            {
                //商家应收款
                poiReceive = TryParse(objpoi_receive_detail_yuan.poiReceive);

                //--------------------------------------------------美团承担明细 
                if (objpoi_receive_detail_yuan.actOrderChargeByMt != null)
                {
                    foreach (actOrderChargeByMt item in objpoi_receive_detail_yuan.actOrderChargeByMt)
                    {
                        order2 = CreateAccount($"美团承担明细-{item.comment}", $"actOrderChargeByMt-{item.feeTypeId}", item.money);
                        list.Add(order2);
                    }
                }

                //--------------------------------------------------商家承担明细 
                //商家活动支出 
                if (objpoi_receive_detail_yuan.actOrderChargeByPoi != null)
                {
                    foreach (actOrderChargeByPoi item in objpoi_receive_detail_yuan.actOrderChargeByPoi)
                    {
                        order2 = CreateAccount($"商家活动支出-{item.comment}", $"actOrderChargeByPoi-{item.feeTypeId}", "-" + item.money);
                        list.Add(order2);
                    }
                }

                //平台服务费
                order2 = CreateAccount("平台服务费", "foodShareFeeChargeByPoi", "-" + objpoi_receive_detail_yuan.foodShareFeeChargeByPoi);
                list.Add(order2);

                //履约服务费
                if (objpoi_receive_detail_yuan.reconciliationExtras != "")
                {
                    reconciliationExtras objreconciliationExtras = JsonConvert.DeserializeObject<reconciliationExtras>(objpoi_receive_detail_yuan.reconciliationExtras);
                    order2 = CreateAccount("履约服务费", "performanceServiceFee", "-" + objreconciliationExtras.performanceServiceFee);
                    list.Add(order2);

                    //6 闪购企客模式
                    if (objreconciliationExtras.chargeMode == 6)
                    {
                        order2 = CreateAccount("技术服务费", "technicalServiceFee", "-" + objreconciliationExtras.technicalServiceFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("距离收费", "distanceFee", "-" + objreconciliationExtras.distanceFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("时段增值收费", "slaFee", "-" + objreconciliationExtras.slaFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("基础配送费", "baseShippingAmount", "-" + objreconciliationExtras.baseShippingAmount.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("品类加价", "categoryChargeFee", "-" + objreconciliationExtras.categoryChargeFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("重量收费", "weightChargeFee", "-" + objreconciliationExtras.weightChargeFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("特殊日期收费", "holidayChargeFee", "-" + objreconciliationExtras.holidayChargeFee.ToString());
                        list.Add(order2);
                    }
                }
            }

            return list;
        }

        private List<SHKF.B2C.Model.Entity.Order.OrderDetailEntity> CreateOrderDetail(string detial, long order_id, long app_poi_code)
        {
            string json = HttpUtility.UrlDecode(detial);
            List<OrderDetailPush> list2 = JsonConvert.DeserializeObject<List<OrderDetailPush>>(json);

            List<SHKF.B2C.Model.Entity.Order.OrderDetailEntity> list = new List<SHKF.B2C.Model.Entity.Order.OrderDetailEntity>();
            foreach (OrderDetailPush orderDetailPush in list2)
            {
                SHKF.B2C.Model.Entity.Order.OrderDetailEntity orderDetailEntity = new SHKF.B2C.Model.Entity.Order.OrderDetailEntity();

                orderDetailEntity.FKSN = order_id;
                orderDetailEntity.actual_price = orderDetailPush.actual_price;
                orderDetailEntity.original_price = orderDetailPush.actual_price;
                orderDetailEntity.app_medicine_code = orderDetailPush.app_medicine_code;
                orderDetailEntity.product_name = orderDetailPush.food_name;
                orderDetailEntity.upc = orderDetailPush.upc;
                orderDetailEntity.qty = orderDetailPush.quantity;
                orderDetailEntity.price = orderDetailPush.price;
                orderDetailEntity.box_num = orderDetailPush.box_num;
                orderDetailEntity.box_price = orderDetailPush.box_price;
                orderDetailEntity.unit = orderDetailPush.unit;
                orderDetailEntity.food_discount = orderDetailPush.food_discount;
                orderDetailEntity.weight = orderDetailPush.weight;
                orderDetailEntity.weight_unit = orderDetailPush.weight_unit;
                list.Add(orderDetailEntity);
            }
            return list;
        }

        private B2C.Model.Entity.Order.OrderAccountEntity CreateAccount(string title, string keyWord, string value)
        {
            B2C.Model.Entity.Order.OrderAccountEntity order2 = new B2C.Model.Entity.Order.OrderAccountEntity();
            order2.Title = title;
            order2.KeyWord = keyWord;
            order2.Value = TryParse(value);
            return order2;
        }


        #endregion

        #region Cancel/CallBack

        [HttpPost("Cancel/CallBack")]
        public async Task<BaseDataDto> Cancel([FromForm] CancelOrderPush order)
        {
            try
            {
                if (order != null && order.app_poi_code > 0)
                {
                    string json = JsonConvert.SerializeObject(order);

                    base.AddLog("Cancel-Order-CallBack->json:" + json);
                    base.WriteInformation("Cancel-Order-CallBack", "jsonData:" + json);

                    int shopSN = 0;
                    ShopMapEntity shopMap = this.shopMapBll.GetShop(order.app_poi_code, PlatformEnum.Mtsg);
                    if (shopMap != null)
                    {
                        shopSN = shopMap.ShopSN;
                    }

                    ReturnOrderContentEntity orderEntity = new ReturnOrderContentEntity();
                    orderEntity.app_poi_code = order.app_poi_code;
                    orderEntity.ShopSN = shopSN;
                    orderEntity.status = 21; //终审已同意 
                    orderEntity.order_id = order.order_id;
                    orderEntity.Platform = PlatformEnum.Mtsg;
                    orderEntity.pDate = DateTime.Now;
                    orderEntity.reason = HttpUtility.UrlDecode(order.reason);

                    OrderContentEntity orderContentEntity = this.mtsgOrderBLL.Query(order.app_poi_code, order.order_id);
                    List<ReturnOrderDetailEntity> list = new List<ReturnOrderDetailEntity>();
                    if (orderContentEntity != null)
                    {
                        orderEntity.total = orderContentEntity.total;
                        orderEntity.ctime = orderContentEntity.ctime;

                        List<OrderDetailEntity> detailList = this.mtsgOrderBLL.QueryDetail(orderContentEntity.SN);

                        //明细
                        foreach (OrderDetailEntity food in detailList)
                        {
                            ReturnOrderDetailEntity detail = new ReturnOrderDetailEntity();
                            detail.FKSN = 0;
                            detail.app_medicine_code = food.app_medicine_code;
                            detail.product_name = food.product_name;
                            detail.price = food.price;
                            detail.qty = food.qty;
                            detail.upc = food.upc;
                            //detail.spec = food.sp;
                            detail.box_num = food.box_num;
                            detail.box_price = food.box_price;
                            detail.refund_price = food.price;
                            //detail.ProductSN = food.ProductSN;
                            detail.unit = food.unit;

                            list.Add(detail);
                        }

                        this.retrunOrderBLL.SaveAll(orderEntity, list);
                    }
                    else //处方药必须通过接口获取
                    {
                        OrderDetailDto orderData = await Detail(order.app_poi_code, order.order_id);
                        if (orderData != null)
                        {
                            orderEntity.total = orderData.data.total;
                            orderEntity.ctime = DateTimeUtil.TimeStampToDateTime(orderData.data.ctime);

                            //订单商品详情
                            if (!string.IsNullOrEmpty(orderData.data.detail))
                            {
                                List<OrderDetailEntity> detailList = MtsgCreateOrderDetail(orderData.data.detail, orderEntity.order_id, orderEntity.app_poi_code);
                                foreach (OrderDetailEntity food in detailList)
                                {
                                    ReturnOrderDetailEntity detail = new ReturnOrderDetailEntity();
                                    detail.FKSN = 0;
                                    detail.app_medicine_code = food.app_medicine_code;
                                    detail.product_name = food.product_name;
                                    detail.price = food.price;
                                    detail.qty = food.qty;
                                    detail.upc = food.upc;
                                    detail.box_num = food.box_num;
                                    detail.box_price = food.box_price;
                                    detail.refund_price = food.price;
                                    detail.unit = food.unit;

                                    list.Add(detail);
                                }

                                this.retrunOrderBLL.SaveAll(orderEntity, list);
                            }

                            //订单优惠信息
                            if (!string.IsNullOrEmpty(orderData.data.extras))
                            {

                            }

                            //订单维度的商家对账信息
                            if (!string.IsNullOrEmpty(orderData.data.poi_receive_detail_yuan))
                            {

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.segContext.Context.Span.ErrorOccurred(ex, null);
                base.WriteException("CallBack", ex);
            }

            BaseDataDto dto = new BaseDataDto();
            dto.data = "ok";
            return dto;
        }
        #endregion

        #region CreateHisOrder

        [HttpGet("CreateHisOrder")]
        public async Task<BaseDataDto> CreateHisOrder(long app_poi_code = 0, long orderid = 0)
        {
            BaseDataDto dto = new BaseDataDto();
            try
            {
                List<long> shopList = new List<long>();

                if(app_poi_code == 0) //如果不指定商店
                {
                    //查询所有商店
                    List<ShopMapEntity> shopMaps = shopMapBll.Query(-1, PlatformEnum.Mtsg);

                    foreach (ShopMapEntity shopMapEntity in shopMaps)
                    {
                        shopList.Add(shopMapEntity.app_poi_code);
                    }
                }
                else
                {
                    shopList.Add(app_poi_code);
                }
                   
                foreach (long apppoicode in shopList)
                {
                    if (orderid == 0)
                    { 
                        OrderIdByDaySeqDto dtoSeq = await this.getOrderIdByDaySeq(apppoicode, 0);
                        if (dtoSeq.error == null)
                        {
                            OrderIdByDaySeqData data = JsonConvert.DeserializeObject<OrderIdByDaySeqData>(dtoSeq.data); 
                            foreach (long order_id in data.order_ids)
                            {
                                SaveHisData(apppoicode, order_id);
                            }
                        } 
                    }
                    else
                    {
                        SaveHisData(apppoicode, orderid);
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return dto;
        }

        private async void SaveHisData(long app_poi_code, long order_id)
        {
            //查看数据库是否存在
            bool bOK = this.mtsgOrderBLL.IsExist(app_poi_code, order_id);
            if (!bOK) //不纯再
            {
                OrderDetailDto orderdto = await Detail(app_poi_code, order_id);

                if (orderdto != null)
                {
                    decimal poiReceive = 0;

                    OrderDetailData orderData = orderdto.data;

                    //返回账目
                    List<SHKF.B2C.Model.Entity.Order.OrderAccountEntity> accounts = CreateHisOrderAccount(orderData, out poiReceive);

                    //定单
                    OrderContentEntity orderEntity = MtsgCreateHisOrder(orderData);
                    orderEntity.poiReceive = poiReceive;

                    //明细
                    List<OrderDetailEntity> list = MtsgCreateOrderDetail(orderData.detail, order_id, app_poi_code);

                    this.mtsgOrderBLL.SaveAll(orderEntity, list, accounts);
                }

            }
        }

        private OrderContentEntity MtsgCreateHisOrder(OrderDetailData order)
        {
            OrderContentEntity orderEntity = new OrderContentEntity();
            orderEntity.app_poi_code = order.app_poi_code;
            orderEntity.ID = order.order_id.ToString();
            orderEntity.status = order.status;
            orderEntity.order_id = order.order_id;
            orderEntity.wm_order_id_view = order.wm_order_id_view;
            orderEntity.wm_poi_name = HttpUtility.UrlDecode(order.wm_poi_name);
            orderEntity.wm_poi_address = HttpUtility.UrlDecode(order.wm_poi_address);
            orderEntity.wm_poi_phone = order.wm_poi_phone;
            orderEntity.recipient_address = HttpUtility.UrlDecode(order.recipient_address);
            orderEntity.recipient_phone = order.recipient_phone;
            orderEntity.recipient_name = HttpUtility.UrlDecode(order.recipient_name);
            orderEntity.shipping_fee = order.shipping_fee;
            orderEntity.total = order.total;
            orderEntity.original_price = order.original_price;
            orderEntity.caution = HttpUtility.UrlDecode(order.caution);
            orderEntity.shipper_phone = order.shipper_phone;
            orderEntity.shipper_phone = order.shipper_phone;
            orderEntity.has_invoiced = order.has_invoiced;
            orderEntity.invoice_title = order.invoice_title;
            orderEntity.Platform = PlatformEnum.Mtsg;
            orderEntity.ctime = DateTimeUtil.TimeStampToDateTime(order.ctime);
            orderEntity.utime = DateTimeUtil.TimeStampToDateTime(order.utime);
            orderEntity.package_bag_money_yuan = order.package_bag_money_yuan.ToString();

            //string strExtras = HttpUtility.UrlDecode(order.extras);
            //[{"mt_charge":0.0,"poi_charge":4.0,"reduce_fee":4.0,"remark":"减配送费5.0元","type":25}]
            //List<extras> obj = JsonConvert.DeserializeObject<List<extras>>(strExtras); 

            if (order.delivery_time == 0)
            {
                orderEntity.delivery_time = new DateTime(1900, 1, 1);
            }
            else
            {
                orderEntity.delivery_time = DateTimeUtil.TimeStampToDateTime(order.delivery_time);
            }

            orderEntity.day_seq = order.day_seq;

            orderEntity.total_weight = order.total_weight;
            return orderEntity;
        }

        private List<SHKF.B2C.Model.Entity.Order.OrderAccountEntity> CreateHisOrderAccount(OrderDetailData order, out decimal poiReceive)
        {
            poiReceive = 0;

            List<SHKF.B2C.Model.Entity.Order.OrderAccountEntity> list = new List<B2C.Model.Entity.Order.OrderAccountEntity>();

            //打包袋金额，单位是元
            B2C.Model.Entity.Order.OrderAccountEntity order2 = CreateAccount("打包袋金额", "package_bag_money_yuan", order.package_bag_money_yuan.ToString());
            list.Add(order2);

            string strpoi_receive_detail_yuan = HttpUtility.UrlDecode(order.poi_receive_detail_yuan);
            poi_receive_detail_yuan objpoi_receive_detail_yuan = JsonConvert.DeserializeObject<poi_receive_detail_yuan>(strpoi_receive_detail_yuan);
            if (objpoi_receive_detail_yuan != null)
            {
                //商家应收款
                poiReceive = TryParse(objpoi_receive_detail_yuan.poiReceive);

                //--------------------------------------------------美团承担明细 
                if (objpoi_receive_detail_yuan.actOrderChargeByMt != null)
                {
                    foreach (actOrderChargeByMt item in objpoi_receive_detail_yuan.actOrderChargeByMt)
                    {
                        order2 = CreateAccount($"美团承担明细-{item.comment}", $"actOrderChargeByMt-{item.feeTypeId}", item.money);
                        list.Add(order2);
                    }
                }

                //--------------------------------------------------商家承担明细 
                //商家活动支出 
                if (objpoi_receive_detail_yuan.actOrderChargeByPoi != null)
                {
                    foreach (actOrderChargeByPoi item in objpoi_receive_detail_yuan.actOrderChargeByPoi)
                    {
                        order2 = CreateAccount($"商家活动支出-{item.comment}", $"actOrderChargeByPoi-{item.feeTypeId}", "-" + item.money);
                        list.Add(order2);
                    }
                }

                //平台服务费
                order2 = CreateAccount("平台服务费", "foodShareFeeChargeByPoi", "-" + objpoi_receive_detail_yuan.foodShareFeeChargeByPoi);
                list.Add(order2);

                //履约服务费
                if (objpoi_receive_detail_yuan.reconciliationExtras != "")
                {
                    reconciliationExtras objreconciliationExtras = JsonConvert.DeserializeObject<reconciliationExtras>(objpoi_receive_detail_yuan.reconciliationExtras);
                    order2 = CreateAccount("履约服务费", "performanceServiceFee", "-" + objreconciliationExtras.performanceServiceFee);
                    list.Add(order2);

                    //6 闪购企客模式
                    if (objreconciliationExtras.chargeMode == 6)
                    {
                        order2 = CreateAccount("技术服务费", "technicalServiceFee", "-" + objreconciliationExtras.technicalServiceFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("距离收费", "distanceFee", "-" + objreconciliationExtras.distanceFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("时段增值收费", "slaFee", "-" + objreconciliationExtras.slaFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("基础配送费", "baseShippingAmount", "-" + objreconciliationExtras.baseShippingAmount.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("品类加价", "categoryChargeFee", "-" + objreconciliationExtras.categoryChargeFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("重量收费", "weightChargeFee", "-" + objreconciliationExtras.weightChargeFee.ToString());
                        list.Add(order2);

                        order2 = CreateAccount("特殊日期收费", "holidayChargeFee", "-" + objreconciliationExtras.holidayChargeFee.ToString());
                        list.Add(order2);
                    }
                }
            }

            return list;
        }

        #endregion
         
        [HttpPost("ToFormData")]
        public string ToFormData(OrderPush order)
        {
            Type tt = order.GetType();

            string fromData = "";
            foreach(PropertyInfo pro in tt.GetProperties())
            {
                fromData += $"{pro.Name}:{pro.GetValue(order)}";
                fromData += "\r\n";
            }

            return fromData;
        }

        [HttpGet("ToFormData/text")]
        public string ToFormData(string text)
        {
            string fromData = "";

            string[] array1 = text.Split("&");
            foreach(string kv in array1)
            {
                string[] array2 = kv.Split("=");

                fromData += $"{array2[0]}:{array2[1]}";
                fromData += "\r\n";
            }

            return fromData;
        }

        [HttpPost("ToJsonData")]
        public OrderPush ToJsonData(OrderPush order)
        {
            order.wm_poi_name = HttpUtility.UrlDecode(order.wm_poi_name);
            order.wm_poi_address = HttpUtility.UrlDecode(order.wm_poi_address);

            order.recipient_address = HttpUtility.UrlDecode(order.recipient_address);
            order.recipient_phone = order.recipient_phone;
            order.recipient_name = HttpUtility.UrlDecode(order.recipient_name); 
            order.caution = HttpUtility.UrlDecode(order.caution);
             
            order.poi_receive_detail_yuan = HttpUtility.UrlDecode(order.poi_receive_detail_yuan);
            order.poi_receive_detail = HttpUtility.UrlDecode(order.poi_receive_detail);
            order.detail = HttpUtility.UrlDecode(order.detail);
            order.extras = HttpUtility.UrlDecode(order.extras);
            order.sku_benefit_detail = HttpUtility.UrlDecode(order.sku_benefit_detail);
            order.extras = HttpUtility.UrlDecode(order.extras);
            return order;
        }
         
        private decimal TryParse(string value)
        {
            decimal result = 0;
            if (decimal.TryParse(value, out result))
            {
                return result;
            };
            return 0;
        }
         
        [HttpGet("list")]
        public OrderListDto List(long shopSN, int status, DateTime create_start, DateTime create_end, int logistics_status = -1)
        {
            //定单列表

            OrderListDto dto = new OrderListDto();
            try
            {
                List<OrderContentEntity> orderList = this.mtsgOrderBLL.Query(shopSN, status, create_start, create_end, logistics_status);
                foreach (OrderContentEntity orderEntity in orderList)
                {  
                    orderEntity.Detail = this.mtsgOrderBLL.QueryDetail(orderEntity.SN);  
                    orderEntity.Accounts = this.orderBLL.QueryAccounts(orderEntity.SN);
                }
                dto.Data = orderList;
            }
            catch (Exception ex)
            {
                dto = new OrderListDto();
                dto.error = new Error() { code = -1, msg = ex.Message };
                base.WriteException("List", ex);
            }
            return dto;
        }

        [HttpGet("Detail")]
        public async Task<OrderDetailDto> Detail(long app_poi_code = 13587900, long order_id = 135879001304545648)
        {
            TokenMeiTuanDto token = await this.GetMtsgToken(app_poi_code);
            return await this.httpClientMeiTuanShanGou.GetOrderDetail(order_id);
        }
 
        [HttpGet("getOrderIdByDaySeq")]
        public async Task<OrderIdByDaySeqDto> getOrderIdByDaySeq(long app_poi_code,int date_time)
        { 
            TokenMeiTuanDto token = await this.GetMtsgToken(app_poi_code);
            return await this.httpClientMeiTuanShanGou.GetOrderIdByDaySeq(app_poi_code, date_time);
        }
    }
}
